//
//  NSDictionary+Safe.m
//  YYBaseClass
//
//  Created by xn on 2022/1/5.
//

#import "NSDictionary+Safe.h"
#import <objc/runtime.h>

@implementation NSDictionary (Safe)

- (id)safeObjectForKey:(id)key{
    if (key != nil) {
        if ([self respondsToSelector:@selector(objectForKey:)]) {
            return [self objectForKey:key];
        }
    }
    return nil;
}

@end

@interface NSMutableDictionary ()

@property (nonatomic, strong) NSRecursiveLock * km_safe_dict_lock;

@end

@implementation NSMutableDictionary (Safe)


+(NSMutableDictionary *)dictionaryWith:(void(^)(NSMutableDictionary *make))block;
{
    NSMutableDictionary *paramsMaker = [NSMutableDictionary dictionaryWithCapacity:0];
    !block?:block(paramsMaker);
    return paramsMaker;
}


-(NSMutableDictionary * (^)(NSString *key, id object))add{
    return ^id(NSString *key, id object){
        if (key.length > 0 && object) {
//            if (!(([object isKindOfClass:[NSString class]] && [object length] <=0)
//               // || ([object isKindOfClass:[NSNumber class]] && [object integerValue] <= 0)
//                )) {
//               [self addEntriesFromDictionary:@{key:object}];
//            }
            [self addEntriesFromDictionary:@{key:object}];
        }
        return self;
    };
}

-(NSMutableDictionary * (^)(NSDictionary *params))append{
    return ^id(NSDictionary *params){
        if ([params isKindOfClass:[NSDictionary class]] && params.count > 0) {
            [self addEntriesFromDictionary:params];
        }
        return self;
    };
}


- (void)safeSetObject:(id)object forKey:(id)key{
    if (key != nil && object != nil) {
        [self.km_safe_dict_lock lock];
        [self setObject:object forKey:key];
        [self.km_safe_dict_lock unlock];
    }
}

- (void)setKm_safe_dict_lock:(NSRecursiveLock *)km_safe_dict_lock
{
    objc_setAssociatedObject(self, @"km_safe_dict_lock",km_safe_dict_lock , OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSRecursiveLock *)km_safe_dict_lock
{
    NSRecursiveLock * lock = objc_getAssociatedObject(self, @"km_safe_dict_lock");
    if (nil == lock) {
        lock = [NSRecursiveLock new];
        [self setKm_safe_dict_lock:lock];
    }
    return lock;
}

- (void)safeRemoveObjectForKey:(id)key {
    
    if (key != nil) {
        [self.km_safe_dict_lock lock];
        [self removeObjectForKey:key];
        [self.km_safe_dict_lock unlock];
    }
}


@end
